package com.cloudz.iptv.bing;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;

import com.cloudz.iptv.R;
import com.cloudz.iptv.activity.BaseActivity;
import com.cloudz.iptv.api.v1.BingServiceApi;
import com.cloudz.iptv.utils.InPutJson;
import com.cloudz.iptv.utils.ResponseUtils;
import com.cloudz.iptv.utils.RetrofitUtils;
import com.cloudz.iptv.utils.SimplePreference;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 验证接口
 */
public class BingConnectActivity extends BaseActivity
{


    @Override
    public int getLayoutId()
    {
        return R.layout.activity_bing_connect_server;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        bingInit();
    }

    /**
     * 绑定初始化
     */
    private void bingInit()
    {

        String deviceId = SimplePreference.getDeviceId(BingConnectActivity.this);

        // 验证绑定情况
        BingServiceApi bingServiceApi = RetrofitUtils.getInstance().createApi(SimplePreference.getServerUrl(BingConnectActivity.this), BingServiceApi.class);

        bingServiceApi.bindInit(deviceId).enqueue(new Callback<ResponseBody>()
        {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
            {

                int code = response.code();
                if (code == 200)
                {
                    try
                    {
                        InPutJson inOutJson = ResponseUtils.getInOutJson(response);

                        if (inOutJson.result)
                        {
                            Intent intent = new Intent(BingConnectActivity.this, BingQrActivity.class);
                            intent.putExtra("qr", inOutJson.data);
                            startActivity(intent);
                            finish();
                        } else
                        {
                            showToast(inOutJson.msg);
                        }
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                        showToastError();
                    }
                } else
                {
                    breakError();
                }


            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {
                breakError();
            }

        });

    }

    private void breakError()
    {
        //延迟1S跳转
        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {

                Intent intent = new Intent(BingConnectActivity.this, BingErrorActivity.class);
                startActivity(intent);
                finish();
            }
        }, 1000);

    }
}
